package com.mdinic.blogovi.front.page.person;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;

import com.mdinic.blogovi.front.common.AbstractBasePage;
import com.mdinic.blogovi.model.Person;

/**
 * Class that represents persons list page.
 * 
 * @author mdinic
 */
public class PersonTopPage extends AbstractBasePage {

    private static final long serialVersionUID = 1L;

    private final int firstResult = MAX_RESULTS;
    private static final int MAX_RESULTS = 30;

    private final List<Person> list = new ArrayList<Person>();

    final AjaxLink<Void> more;
    private int page = 1;

    /**
     * Constructor.
     */
    public PersonTopPage() {
        super(false);

        list.addAll(Person.findTopPersons(0, MAX_RESULTS));
        final PersonTopPanel personTopPanel = new PersonTopPanel(PANEL, list);
        personTopPanel.setOutputMarkupId(true);
        add(personTopPanel);

        page = 1;
        more = new AjaxLink<Void>("more_link") {

            private static final long serialVersionUID = 1L;

            @Override
            public void onClick(AjaxRequestTarget target) {

                List<Person> toAdd = Person.findTopPersons(firstResult * page, MAX_RESULTS);

                if (!toAdd.isEmpty()) {
                    list.addAll(toAdd);
                    target.add(personTopPanel);
                    page++;
                } else {
                    more.setEnabled(false);
                    target.add(more);
                }
            }
        };
        more.setOutputMarkupId(true);
        add(more);
    }
}
